package com.cartoonrabbit.controller;


import cn.hutool.core.util.RandomUtil;
import com.cartoonrabbit.pojo.User;
import com.cartoonrabbit.service.IUserService;
import com.cartoonrabbit.vo.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiuTeng
 * @since 2023-01-08
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value ="制作次数操作")
    @PostMapping("/production/change/{times}")
    @PreAuthorize("@ss.permitAll()")
    public RespBean productionChange(@PathVariable Integer times, Principal principal){
        if (ObjectUtils.isEmpty(principal)||ObjectUtils.isEmpty(principal.getName())){
            return RespBean.fail(401,"用户为授权，请重新登录");
        }
        if (ObjectUtils.isEmpty(times)||times<=0){
            return RespBean.fail("参数异常");
        }
        return userService.productionChange(times,principal.getName());
    }

    @ApiOperation(value ="看广告得红包")
    @PostMapping("/viewAd/redbag")
    @PreAuthorize("@ss.permitAll()")
    public RespBean productionChange(Principal principal){
        if (ObjectUtils.isEmpty(principal)||ObjectUtils.isEmpty(principal.getName())){
            return RespBean.fail(401,"用户为授权，请重新登录");
        }
        int i = RandomUtil.randomInt(1, 3);
        User user = userService.getById(principal.getName());
        user.setBalance(user.getBalance()+i);
        userService.updateById(user);
        Map<String,Object> res=new HashMap<>();
        res.put("money",i);
        res.put("userInfo",user);
        return RespBean.success("SUCCESS",res);
    }

    @ApiOperation(value = "获取用户唯一标识")
    @GetMapping("/useronlyId")
    @PreAuthorize("@ss.permitAll()")
    public RespBean getUserInfo(Principal principal){
        if (principal==null){
            return new RespBean(401,"未登录",null);
        }
        return RespBean.success("SUCCESS",principal.getName());
    }

}
